<template>
  
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">

    <template slot="title">
      <div style="width: 100%;">
        <span>{{ title }}</span>
        <span style="display:inline-block;width:calc(100% - 51px);padding-right:10px;text-align: right">
          <a-button @click="toggleScreen" icon="appstore" style="height:20px;width:20px;border:0px"></a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
      
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="企业名称">
          <a-input placeholder="请输入企业名称" v-decorator="['companyName', validatorRules.required]" />
        </a-form-item>


        <a-form-item label="请上传封面图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            listType="picture-card"
            class="business-uploader"
            :showUploadList="false"
            :action="uploadAction"
            :data="{'isup':1}"
            :headers="headers"
            :beforeUpload="beforeUpload"
            @change="handleChange2"
          >
            <img v-if="picUrl2" :src="getFaceImgView()" alt="封面图片" style="height:204px;max-width:500px"/>
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>







        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="法人信息">
          <a-input placeholder="请输入法人信息" v-decorator="['legalPersonInfo', validatorRules.required]" />
        </a-form-item>





        <a-form-item label="请上传营业执照" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            listType="picture-card"
            class="business-uploader"
            :showUploadList="false"
            :action="uploadAction"
            :data="{'isup':1}"
            :headers="headers"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="picUrl" :src="getBusinessLicenseView()" alt="营业执照" style="height:204px;max-width:500px"/>
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="税号">
          <a-input placeholder="请输入税号" v-decorator="['ein', validatorRules.required]" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="统一信用码">
          <a-input placeholder="请输入统一信用码" v-decorator="['creditCode', validatorRules.required]" />
        </a-form-item>


        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="工商注册号">
          <a-input placeholder="请输入工商注册号" v-decorator="['registrationNumber', validatorRules.required]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="组织机构码">
          <a-input placeholder="请输入统一信用码" v-decorator="['organizationCode', validatorRules.required]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="公司简介">
          <a-input placeholder="请输入公司简介" v-decorator="['companyProfile', validatorRules.required]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="发展历程">
          <a-input placeholder="请输入发展历程" v-decorator="['development', validatorRules.required]" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="注册资金">
          <a-input placeholder="请输入注册资金" v-decorator="['registeredCapital', validatorRules.registeredCapital]" />
        </a-form-item>


        <a-form-item label="成立日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-date-picker
            style="width: 100%"
            placeholder="请输入成立日期"
            v-decorator="['establishDate', {initialValue:!model.establishDate?null:moment(model.establishDate,dateFormat)}]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="企业类型">
          <a-input placeholder="请输入企业类型" v-decorator="['companyType', validatorRules.required]" />
        </a-form-item>

        <a-form-item label="执照核准日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-date-picker
            style="width: 100%"
            placeholder="请输入核准日期"
            v-decorator="['approvalDate', {initialValue:!model.approvalDate?null:moment(model.approvalDate,dateFormat)}]"/>
        </a-form-item>
        
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="登记状态">
          <a-input placeholder="请输入登记状态" v-decorator="['registrationStatus', validatorRules.required]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="执照登记机关">
          <a-input placeholder="请输入登记机关" v-decorator="['registrationAuthority', validatorRules.required]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="企业地址">
          <a-input placeholder="请输入企业地址" v-decorator="['address', validatorRules.required]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="手机号码">
          <a-input placeholder="请输入手机号码" :disabled="isDisabledAuth('user:form:phone')" v-decorator="['cphone',validatorRules.phone]" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="座机">
          <a-input placeholder="请输入座机"    v-decorator="['telphone',validatorRules.required]" />
        </a-form-item>
        
        
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="经营范围">
          <a-input placeholder="请输入经营范围" v-decorator="['businessScope', {}]" />
        </a-form-item>
        
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="公司官网">
          <a-input placeholder="请输入公司官网" v-decorator="['website', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="公众号">
          <a-input placeholder="请输入公众号" v-decorator="['officialAccounts', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="微博">
          <a-input placeholder="请输入微博" v-decorator="['microblog', {}]" />
        </a-form-item>
		
      </a-form>
    </a-spin>
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from 'moment'
  import Vue from 'vue'
  // 引入搜索部门弹出框的组件
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import { getAction } from '@/api/manage'
  import { disabledAuthFilter } from "@/utils/authFilter"
  import {duplicateCheck } from '@/api/api'

  export default {
    name: "ConsumersModal",
    
    data () {
      return {
        drawerWidth:700,
        modaltoggleFlag:true,
        confirmDirty: false,
        disableSubmit:false,
        userId:"", //保存用户id
        dateFormat:"YYYY-MM-DD",
        validatorRules:{
          required:{
            rules: [{
              required: true, message: '此为必填项,请输入相关信息!'
            }]

          },
          
          
          phone:{
            rules: [{
              required: true, message: '请输入联系方式!'
            },{
              validator: this.validatePhone,
            }]
            },

          registeredCapital:{
            rules: [{
              required: true, message: '请输入注册资金!'
            },{
              validator: this.validateNum,
            }]
            },

          // email:{
          //   rules: [{
          //     validator: this.validateEmail
          //   }],
          // },
          roles:{},
          //  sex:{initialValue:((!this.model.sex)?"": (this.model.sex+""))}
          // telephone: {
          //   rules: [
          //     { pattern: /^0\d{2,3}-[1-9]\d{6,7}$/, message: '请输入正确的座机号码' },
          //   ]
          // }
        },
        title:"操作",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        uploadLoading:false,
        confirmLoading: false,
        headers:{},
        picUrl: "",
        picUrl2: "",
        form: this.$form.createForm(this),
        url: {
          fileUpload: window._CONFIG['domianURL']+"/sys/common/upload",
          userId:"/consumers/generateUserId", // 引入生成添加用户情况下的url
          imgerver: window._CONFIG['domianURL']+"/sys/common/view",
          add: "/consumers/add",
          edit: "/consumers/edit",
        },
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token}
    },
    computed:{
      uploadAction:function () {
        return this.url.fileUpload;
      }
    },
    methods: {
      isDisabledAuth(code){
        return disabledAuthFilter(code);
      },
      //窗口最大化切换
      toggleScreen(){
        if(this.modaltoggleFlag){
          this.modalWidth = window.innerWidth;
        }else{
          this.modalWidth = 800;
        }
        this.modaltoggleFlag = !this.modaltoggleFlag;
      },

      refresh () {
          this.userId=""
      },

      add () {
        this.picUrl = "";
        this.picUrl2 ="";
        this.refresh();
        this.edit({activitiSync:'1'});
      },
      edit (record) {
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        let that = this;
        this.form.resetFields();
        if(record.hasOwnProperty("id")){
          this.picUrl = "Has no pic url yet";
          // this.picUrl2= "Has no pic url yet";
        }
        that.userId = record.id;
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model,'companyName','legalPersonInfo','ein','address','businessScope','cphone','website','officialAccounts','microblog','approvalDate','registrationAuthority','registrationStatus','businessTerm','registeredCapital','companyType','creditCode','inputType','bindingStatus','registrationNumber','organizationCode','companyProfile','development','telphone'))
        //时间格式化
        });

      },
      close () {
        this.$emit('close');
        this.visible = false;
        this.disableSubmit = false;
      },
      moment,
      getBusinessLicenseView(){
        return this.url.imgerver +"/"+ this.model.businessLicenseImg;
      },

      getFaceImgView(){
        return this.url.imgerver +"/"+ this.model.faceImg;
      },
      handleSubmit () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let  businessLicenseImg= that.model.businessLicenseImg;
            let  faceImg= that.model.faceImg;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            formData.businessLicenseImg = businessLicenseImg;
            formData.faceImg =faceImg;

            if(!this.model.id){
              formData.id = this.userId;
            }

            //时间格式化
            
            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })



          }
        })
      },
      handleCancel () {
        this.close()
      },

      validateNum(rule, value, callback){
        if(!new RegExp(/^[1-9]\d*$/).test(value)){
            callback("请输入正确的数字格式!")
        }else{
            callback()
        }
      },


      
      
      validatePhone(rule, value, callback){
        if(!value){
          callback()
        }else{
          //update-begin--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
          if(new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)){
            //update-end--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------

            var params = {
              tableName: 'consum_info',
              fieldName: 'cphone',
              fieldVal: value,
              dataId: this.userId
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback("手机号已存在!")
              }
            })
          }else{
            callback("请输入正确格式的手机号码!");
          }
        }
      },
      // validateEmail(rule, value, callback){
      //   if(!value){
      //     callback()
      //   }else{
      //     if(new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)){
      //       var params = {
      //         tableName: 'sys_user',
      //         fieldName: 'email',
      //         fieldVal: value,
      //         dataId: this.userId
      //       };
      //       duplicateCheck(params).then((res) => {
      //         console.log(res)
      //         if (res.success) {
      //           callback()
      //         } else {
      //           callback("邮箱已存在!")
      //         }
      //       })
      //     }else{
      //       callback("请输入正确格式的邮箱!")
      //     }
      //   }
      // },
      
      handleConfirmBlur  (e) {
        const value = e.target.value;
        this.confirmDirty = this.confirmDirty || !!value
      },

      normFile  (e) {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
          return e
        }
        return e && e.fileList
      },
      beforeUpload: function(file){
        var fileType = file.type;
        if(fileType.indexOf('image')<0){
          this.$message.warning('请上传图片');
          return false;
        }
        //TODO 验证文件大小
      },
      handleChange (info) {
        this.picUrl = "";
        if (info.file.status === 'uploading') {
          this.uploadLoading = true;
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response;
          this.uploadLoading = false;
          console.log(response);
          if(response.success){
            this.model.businessLicenseImg = response.message;
            this.picUrl = "Has no pic url yet";
          }else{
            this.$message.warning(response.message);
          }
        }
      },
      handleChange2 (info) {
        this.picUrl2 = "";
        if (info.file.status === 'uploading') {
          this.uploadLoading = true;
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response;
          this.uploadLoading = false;
          console.log(response);
          if(response.success){
            this.model.faceImg = response.message;
            this.picUrl2 = "Has no pic url yet";
          }else{
            this.$message.warning(response.message);
          }
        }
      },





      // 根据屏幕变化,设置抽屉尺寸
      resetScreenSize(){
        let screenWidth = document.body.clientWidth;
        if(screenWidth < 500){
          this.drawerWidth = screenWidth;
        }else{
          this.drawerWidth = 700;
        }
      },

    }
  }
</script>

<style lang="less" scoped>
/** Button按钮间距 */
  .ant-btn {
    margin-left: 30px;
    margin-bottom: 30px;
    float: right;
  }

  .business-uploader > .ant-upload {
    width:204px;
    height:504px;
  }
  .ant-upload-select-picture-card i {
    font-size: 49px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .ant-table-tbody .ant-table-row td{
    padding-top:10px;
    padding-bottom:10px;
  }


</style>